<template>
  <div class="personNav">
    <div class="nav1">
      <nav-header :user="user_name"></nav-header>
    </div>
    <div class="second">
      <div class="left">
        <left-menu></left-menu>
      </div>
      <div class="right">
        <div class="top">
          <el-menu
            :default-active="activeIndex2"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
          >
            <el-menu-item index="1" @click="allPlan">全部计划</el-menu-item>
            <el-menu-item index="2" @click="myPlan">我的计划</el-menu-item>

            <!-- <el-submenu index="2">
              <template slot="title">我的计划</template>
              <el-menu-item index="2-1">选项1</el-menu-item>
              <el-menu-item index="2-2">选项2</el-menu-item>
              <el-menu-item index="2-3">选项3</el-menu-item>
            </el-submenu>-->
            <!-- <el-menu-item index="3">
              <a href="#">计划管理</a>
            </el-menu-item>-->
            <el-menu-item index="4">
              <div>
                <el-button type="text" style="color:#ffffff" @click="newaddplan">新增计划</el-button>
                <el-dialog
                  title="勾选左侧全部任务列表，并加入到右侧计划列表！"
                  :visible.sync="centerDialogVisible"
                  width="35%"
                  center
                >
                  <div class="bottom">
                    <template>
                      <!-- <el-transfer
                        filterable
                        :right-default-checked="value2"
                        :filter-method="filterMethod"
                        filter-placeholder="请输入搜索条件"
                        v-model="value2"
                        :data="data2"
                        :titles="['我的项目', '待生效']"
                        @change="rightChange"
                        @right-check-change="checkChange"
                      ></el-transfer>-->

                      <el-transfer
                        v-model="transferValue"  
                        :left-default-checked="leftDefaultChecked"
                        :right-default-checked="rightDefaultChecked"
                        :data="transferData"
                        @change="rightChange"
                        :titles="['所有项目', '待生效']"
                      ></el-transfer>
                    </template>
                  </div>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="ensureButton">确 定</el-button>
                  </span>
                </el-dialog>
              </div>
            </el-menu-item>
            <div class="search">
              <div class="nav_sear">
                <div class="sea_left">
                  <el-select
                    :clearable="true"
                    :filterable="true"
                    v-model="value1"
                    size="mini"
                    placeholder="请选择计划名称"
                  >
                    <el-option
                      v-for="item in plan_lis"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>

                <div class="sea_middle">
                  <el-select
                    v-model="valueUser"
                    collapse-tags
                    style="margin-left: 20px;"
                    placeholder="请选择创建人"
                    size="mini"
                    :clearable="true"
                    :filterable="true"
                  >
                    <el-option
                      v-for="item in creater_lis"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>
                <div class="sea_right">
                  <el-select
                    v-model="value3"
                    size="mini"
                    :filterable="true"
                    :clearable="true"
                    placeholder="请选择模块"
                  >
                    <el-option
                      v-for="item in module_lis"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>
                <div class="buttonSearch">
                  <el-button @click="buttSearch" size="mini" type="primary" icon="el-icon-search">查询</el-button>
                </div>
              </div>
              <div class="perform">
                <el-button type="danger" @click="plan_perform" size="medium" icon="el-icon-thumb">全部执行</el-button>
              </div>
            </div>
          </el-menu>
        </div>
        <div class="footer">
          <template>
            <el-table
              ref="multipleTabletableData"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              lazy
              border
              row-key="name"
              :highlight-current-row="true"
              :row-style="rowStyle"

            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="plan_name" label="计划名称">
                <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
              </el-table-column>
              <el-table-column prop="person" label="创建人"></el-table-column>
              <el-table-column prop="create_time" label="创建时间" show-overflow-tooltip></el-table-column>
              <el-table-column prop="update_time" label="修改时间" show-overflow-tooltip></el-table-column>

              <el-table-column label="操作" fixed="right" width="225px">
                <template slot-scope="scope">
                  <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">查看</el-button> -->
                  <el-popover placement="top" width="300" trigger="click">
                    <el-table :data="gridData">
                      <el-table-column width="100" property="plan_name" label="计划名称" show-overflow-tooltip></el-table-column>
                      <el-table-column width="100" property="project_name" label="项目名称" show-overflow-tooltip></el-table-column>
                      <el-table-column width="100" property="module_name" label="模块" show-overflow-tooltip></el-table-column>
                    </el-table>
                    <el-button slot="reference" @click="show(scope.$index,scope.row)" size="mini">详情</el-button>
                  </el-popover>

                  <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- <div style="margin-top: 20px">
              <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button>
              <el-button @click="toggleSelection()">取消选择</el-button>
            </div>-->
          </template>
          <div class="pages">
            <page :item="dic_item" @pageNumber="get_page"></page>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import navHeader from "./../components/NavHeader";
import leftMenu from "@/components/leftMenu";
import page from "@/components/page";
import { api } from "./api/index";
export default {
  data() {
    const generateData = (_) => {
      const data = [];
      for (let i = 1; i <= 15; i++) {
        data.push({
          key: i,
          label: `备选项 ${i}`,
        });
      }
      return data;
    };

    return {
      plan_lis:[],
      leftDefaultChecked: [],
      rightDefaultChecked: [],
      transferData: [], // 全部数据
      transferValue: [1, 4], // 右边数据

      edit_row: {},
      button_soruce: "", // 穿梭框来源
      current_page: 1, // 默认值：1  取组件回传，重新赋值
      dic_item: {
        totalCount: 0,
      },

      tes_lis: [],
      renderFunc(h, option) {
        return <span>{option.label}</span>;
      },
      right_lis: ["登陆"],
      mounted_data: [],
      gridData: [],
      plan_name: "",
      rightValue: [],
      projectname_lis: [],
      centerDialogVisible: false,
      activeIndex: "1",
      activeIndex2: "1",
      user_name: "",
      data2: [],
      value2: [],
      filterMethod(query, item) {
        //return item.pinyin.indexOf(query) > -1;
      },

      tableData: [],
      multipleSelection: [],
      plan_lis: [],
      module_lis: [],
      creater_lis: [],
      value1: "",

      value3: "",
      valueUser: "",
    };
  },
  components: {
    navHeader,
    leftMenu,
    page,
  },
  methods: {
    //  全部执行按钮
    plan_perform(){
      // 通过长度判断是否勾选
      if (this.multipleSelection.length) {
           console.log("plan_perform");
        const plan_lis = JSON.stringify(this.plan_lis)
        localStorage.setItem("cheked",JSON.stringify(plan_lis))  //存储本地
        this.$router.push({
          name:"report",
          params:{
              da:plan_lis
          }
        })
        console.log(plan_lis);
        console.log("有数据");
      }else{
        this.$message({
          type:"fail",
          message:"请先勾选左侧测试计划列表"
        })
        console.log("无数据");
      }

      // 点击全部执行  页面跳转并传值
   
        // api({url:"/api/api/interface/project-list",
        //     method:"POST",
        //     data:this.multipleSelection
        // }).then((da)=>{
        
        //   console.log(da);
        // }).catch((err)=>{
        //   console.log(err);
        // })
    },
    // 勾选右侧触发
    checkChange(arr1, arr2) {
      console.log(arr1);
      console.log(this.value2);
      console.log("888888888888888");
      console.log(arr2);
      // console.log(arr1);
    },
    allPlan() {
      this.form_mouted();
      this.get_searchLis();
    },

    myPlan() {
      console.log("我的计划");

      let user = localStorage.getItem("user");

      let lis = this.tableData;

      let new_lis = [];
      lis.forEach((item) => {
        if (user == item.person) {
          new_lis.push(item);
        }
      });

      this.tableData = new_lis;
    },


    // tabledata设置样式
    rowStyle({ row, rowIndex }) {
      return {
        height: "58px",
      };
    },
    buttSearch() {
      let dic = {
        plan_name: this.plan_lis[this.value1]
          ? this.plan_lis[this.value1].label
          : "",
        person: this.creater_lis[this.valueUser]
          ? this.creater_lis[this.valueUser].label
          : "",
        plan_module: this.module_lis[this.value3]
          ? this.module_lis[this.value3].label
          : "",
      };

      api({
        url: "/interface/select-plan",
        method: "GET",
        params: dic,
      }).then((da) => {
        let res = da.data;
        if (res.status === 10000) {
          this.dic_item.totalCount = res.totalCount;
          let lis = (this.mounted_data = res.data);
          let tem_lis = [];
          lis.forEach((item) => {
            let dic = {
              plan_name: item.plan_name,
              person: item.person,
              create_time: item.create_time,
              update_time: item.update_time,
            };

            tem_lis.push(dic);
          });
          this.tableData = tem_lis;
        }

        console.log("kkkkkkk");
      });
    },

    // 子组件传回翻页页码
    get_page(page_number) {
      this.current_page = page_number;
      this.form_mouted(); //  重新赋值刷新页面
    },

    handleDelete(index, row) {
      this.$confirm('此操作将永久删除本条测试计划，是否继续？','提示',{
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        type:'warning'
      }).then(()=>{
      let dic = {
        plan_name: row.plan_name,
        person: row.person
      };
      
        console.log(dic);
        api({
          url: "/interface/delete-plan",
          method: "POST",
          data: dic,
        }).then((da) => {
          if (da.data.status === 10000) {
            this.$message({
              type: "success",
              message: da.data.msg,
            });
            this.form_mouted();
          }
        });

      }).catch(()=>{
        this.$message({
          type:'info',
          message:'取消删除'
        })
      })

    },
    //  编辑按钮
    async handleEdit(index, row) {
      this.button_soruce = 2; // 来源编辑按钮
      this.edit_row = row; //编辑所在行数据

      console.log(this.button_soruce);
  
      const res = await this.newaddplan()

      const rig_data = await this.show(index,row)   //详情数据

      const res_lis = new Array()  //创建数组

      res.forEach((item)=>{

          res_lis.push(item.label)
    })

      const lis = []
  
      rig_data.forEach(item=>{
          name = item.project_name+">"+item.module_name
          const index_get = res_lis.indexOf(name)
          lis.push(index_get+1)
      })


      console.log(lis);

      this.transferValue = lis

      this.button_soruce = 2; // 来源编辑按钮

    },

    //新增计划 需要渲染左侧穿梭框数据列表
    newaddplan() {

      this.button_soruce=1
      this.centerDialogVisible = !this.centerDialogVisible; // 开启弹窗
      console.log("newaddplan");
      let dic = { project_type: 1 };

      return new Promise((resolve, reject) => {
            api({
              url: "/interface/total-module", // 获取接口首页项目名称
              method: "GET",
              params: dic,
            })
              .then((da) => {
                var data_lis = [];
                let lis = da.data.item;
                lis.forEach((arg) => {
                  let name = arg.project_name;

                  arg.module_name.forEach((mod) => {
                    let dic = {
                      key: data_lis.length + 1,
                      label: name + ">" + mod,
                    };
                    data_lis.push(dic);
                  });
                });
                // console.log(data_lis);
                this.transferData = data_lis;
                this.transferValue = []
                resolve(this.transferData) 
              })
              .catch((err) => {
              reject(err);
              });
      })

      // console.log(data_lis);
      //

      // this.transferData; // 全部数据

      // console.log(this.transferData);
    },

    // 详情列表
    show(index, row) {
      return new  Promise((resolve,reject)=>{
          let lis = this.mounted_data[index].plan_module;
          let plan_name = this.mounted_data[index].plan_name;
          let tem_lis = [];
          lis.forEach((item) => {
            let split_lis = item.split(">")
            let dic ={
                plan_name:plan_name,
                module_name : split_lis[1],
                project_name: split_lis[0]
            }
            tem_lis.push(dic)
          });

          this.gridData = tem_lis;
          
          resolve(this.gridData)

      })

    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    // 勾选时候获取函数
    handleSelectionChange(val) {
      this.multipleSelection = val;   // 勾选赋值
      const plan_lis = []
      val.forEach((item)=>{
        const dic = {}
        this.mounted_data.forEach((da)=>{
          if (da.person == item.person && da.plan_name==item.plan_name) {
            dic.person = da.person
            dic.plan_name  = da.plan_name
            dic.item = da.plan_module
          }
        })
        plan_lis.push(dic)
      })
      
      this.plan_lis = plan_lis



      console.log(this.plan_lis);
      // 获取计划下的所有模块
      // console.log("-==================");
    },
    // 确定按钮  
    ensureButton() {

      console.log(this.button_soruce);
      if (this.button_soruce==1) {
        this.$prompt("请输入计划名称", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          // inputErrorMessage: "计划格式不正确",
        })
          .then(({ value }) => {
            this.plan_name = value;

            let right_Lis = [];
            this.rightValue.forEach((i) => {
              right_Lis.push(i);
            });

            

            let dic_plan = {
              plan_name: value,
              plan_module: right_Lis,
              person: localStorage.getItem("user"),
              sounce:0
            };

            
            console.log(dic_plan);
            console.log("-------");

            api({
              url: "/interface/planAdd",
              method: "POST",
              data: dic_plan,
            })
              .then((da) => {
                if (da.data.status === 10000) {
                  this.$message({
                    type: "success",
                    message: "创建成功，你的计划名称是: " + value,
                  });
                  this.form_mouted();
                } else {
                  this.$message({
                    type: "fail",
                    message: "创建失败，计划名已存在",
                  });
                }
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });

        this.centerDialogVisible = false; //关闭弹窗
      } else {
        this.$confirm("此操作将永久更改计划内容, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(({ value }) => {
            this.plan_name = value;
            let right_Lis = [];
            this.rightValue.forEach((i) => {
              right_Lis.push(i);
            });

            let dic_plan = {
              plan_name: this.edit_row.plan_name,
              plan_module: right_Lis,
              person: localStorage.getItem("user"),
              sounce:1
            };
     

            api({
              url: "/interface/planAdd",
              method: "POST",
              data: dic_plan,
            })
              .then((da) => {
                console.log(da);
                console.log("@@@@@");
                if (da.data.status === 10001) {

                  this.$message({
                    type: "success",
                    message: "更改成功",
                  });
                  this.centerDialogVisible = !this.centerDialogVisible;
                  this.form_mouted();
                } else {
                  this.$message({
                    type: "fail",
                    message: "创建失败",
                  });
                }
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      }
    },
    rightChange(value, direction, keys) {

      // 新增计划赋值transferData所有左侧可选

      let lis = [];
      value.forEach((dex) => {
            lis.push(this.transferData[dex-1].label)
      });

      this.rightValue = lis;  // ["商品管理17>测试模块", "商品管理17>测试模块2"]

    },

    handleSelect(key, keyPath) {
      if (key == 4) {
        var projectname_lis = [];
        let dic = {
          project_type: 1,
        };
        api({
          url: "/interface/total-module", // 获取接口首页项目名称
          method: "GET",
          params: dic,
        })
          .then((da) => {
            let data = []; //
            let lis = da.data.item;
            lis.forEach((di_arg, index) => {
              data.push({
                label: di_arg.project_name,
                key: index,
                pinyin: di_arg.project_name,
                disabled: true,
              });
              this.data2 = data;
              di_arg.module_name.forEach((item_arg, index) => {
                let tem_dic = {};
                data.push({
                  label: item_arg,
                  // key: this.data2.length + 1,
                  key: JSON.stringify([di_arg.project_name, item_arg]),
                  pinyin: item_arg,
                  disabled: false,
                });
              });
              this.data2 = data;

              this.tes_lis = this.data2;
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    func_mouted() {
      this.user_name = localStorage.getItem("user"); // 获取用户名
      let dic = {
        plan_type: "all",
        page: 1,
      };

      let req_arg = {
        url: "/interface/select-plan",
        method: "GET",
        params: dic,
      };

      api(req_arg).then((da) => {
        let res = da.data;

        console.log(da);

        console.log("测试111");
        this.dic_item.totalCount = res.totalCount;
        this.dic_item.req = req_arg;

        if (res.status === 10000) {
          let lis = (this.mounted_data = res.data);
          lis.forEach((item) => {
            let dic = {
              plan_name: item.plan_name,
              person: item.person,
              create_time: item.create_time,
              update_time: item.update_time,
            };

            this.tableData.push(dic);
          });

          console.log(this.mounted_data);

          console.log("func_mouted");
        }
      });
    },
    form_mouted() {
      this.user_name = localStorage.getItem("user"); // 获取用户名
      let dic = {
        plan_type: "all",
        page: this.current_page,
      };
      api({
        url: "/interface/select-plan",
        method: "GET",
        params: dic,
      }).then((da) => {
        let res = da.data;
        if (res.status === 10000) {
          this.dic_item.totalCount = res.totalCount;
          let lis = (this.mounted_data = res.data);
          let tem_lis = [];
          lis.forEach((item) => {
            let dic = {
              plan_name: item.plan_name,
              person: item.person,
              create_time: item.create_time,
              update_time: item.update_time,
            };

            tem_lis.push(dic);
          });
          this.tableData = tem_lis;
        }
      });
    },

    get_searchLis() {
      api({
        url: "/interface/plan-data",
        method: "GET",
        params: "",
      }).then((da) => {
        console.log(da);
        console.log("get22222222");
        let lis = da.data.data;
        console.log(lis);
        this.plan_lis = lis[0].plan_name;
        this.module_lis = lis[1].plan_module;
        this.creater_lis = lis[2].person;
      });
    },
  },
  mounted() {

    console.log("mounted");
    this.func_mouted();
    this.get_searchLis();
  },
};
</script>
<style lang='scss'>
.search {
  display: flex;
  justify-content: space-between;
  .perform {
    line-height: 60px;
    margin-right: 20px;
  }

  .nav_sear {
    height: 60px;
    // background: yellow;
    display: flex;
    justify-content: flex-start;
    .sea_left {
      margin-left: 100px;
      line-height: 60px;
    }
    .sea_middle {
      line-height: 60px;
    }

    .sea_right {
      line-height: 60px;
      margin-left: 20px;
    }

    .buttonSearch {
      line-height: 60px;
      margin-left: 30px;
    }

    // margin-left: 100px;
  }
  // .el-select.el-select--mini {
  //   margin-left: 200px !important;
  // }
}

.personNav {
  .el-transfer-panel {
    width: 180px !important;
  }
  .el-checkbox__label {
    font-size: 10px;

  .el-table td th {
    text-align: center;
  }
  }
  .nav {
    display: flex;
    justify-content: space-between !important;
  }
  height: 100%;
  .second {
    height: calc(100% - 60px);
    display: flex;
    justify-content: flex-start;
    .left {
      height: 100%;
    }
    .right {
      width: 100%;
      .top {
        width: 100%;
        // height: 50px;
        background: #909399;
        color: #c0c4cc;
        line-height: 50px;
        font-size: 16px;
        // padding-left: 20px;
      }
      .footer {
        width: 100%;
        height: calc(100% - 70px);
        // background: #00ff00;
      }
    }
  }
}
</style>








